<script setup lang='ts' name="name">
import type { VxePagerEvents, VxeTableInstance } from 'vxe-table'
import { agreement } from '@fl/api/purchase'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import { FlagStatusEnum, SourceStatusEnum, agreementStatusEnum } from '../../constant'
import { createMapEnum } from '../../mapEnum'

import { useForm } from '../../hooks/use-form'
import { useTable } from '../../hooks/use-table'
import { operateList, operateType } from '../../hooks/use-operate'
import { isAdmin, isPurchaser } from '../../hooks/use-role'

const { useDeleteAgreementMeta, useGetAgreementMetaPage, useInitAgreementMetaInfo, useStopAgreementMetaInfo, useExportExcel } = agreement(isAdmin.value)

const agreementEnum = createMapEnum(agreementStatusEnum)
const sourceEnum = createMapEnum(SourceStatusEnum)
const { gridOptions } = useTable()
const { push } = useRouter()
const { path } = useRoute()
const signPath = path.replace('agreement', 'sign-agreen')
const { form, reset, schema } = useForm()
const searchParams = computed(() => {
    const [startDate, endDate] = form.value.daterange || []
    console.log(startDate, endDate, 'startDate, endDate')

    return {
        agreementType: 1,
        agreementCode: form.value.agreementCode,
        agreementName: form.value.agreementName,
        status: form.value.status,
        partyB: form.value.partyB,
        partyA: form.value.partyA,
        startDate,
        endDate,
        page: gridOptions.pagerConfig.currentPage,
        size: gridOptions.pagerConfig.pageSize,
    }
})
const { data, isLoading } = useGetAgreementMetaPage(searchParams)

const { isPending, mutate } = useStopAgreementMetaInfo()

const { isPending: exportAgrenIsPending, mutate: exportAgreen } = useExportExcel()
const { isPending: initAgrenIsPending, mutate: initAgreen } = useInitAgreementMetaInfo()
const { isPending: deleteAgrenIsPending, mutate: deleteAgreen } = useDeleteAgreementMeta()
const tableRef = ref<VxeTableInstance<any>>()
const tableLoading = computed(() => isPending.value || isLoading.value || initAgrenIsPending.value || deleteAgrenIsPending.value)

function goShow(row: any) {
    push({
        path: signPath,
        query: {
            id: row.id,
        },
    })
}

function addShow() {
    push({
        path: signPath,
    })
}

function goInitialA(row: any) {
    initAgreen(row.id, {
        onSuccess: () => {
            ElMessage.success('发起成功')
            goShow(row)
        },
    })
}

function stopInfo(row: any) {
    ElMessageBox.confirm('是否确认停用?', '提示', { type: 'warning' })
        .then(() => {
            mutate(row.id, {
                onSuccess: () => {
                    ElMessage.success('停用成功')
                },
            })
        })
}

// function showAdd(row: any) {
//     return row.agreementState === 4 && row.agreementType === 2
// }
function searchSubmit(value: any) {
    console.log('searchSubmit', value)
    form.value = { ...value }
    // refetch()
}
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    gridOptions.pagerConfig.currentPage = currentPage
    gridOptions.pagerConfig.pageSize = pageSize
}
watchEffect(() => {
    if (data.value) {
        gridOptions.data = cloneDeep(data.value?.records) ?? []
        gridOptions.pagerConfig.total = data.value?.total ?? 0
    }
})
function initialAHandler(row: any) {
    ElMessageBox.confirm('是否确认发起协议?', '提示', { type: 'warning' })
        .then(() => {
            goInitialA(row)
        })
}
function deleteDraf(row: any) {
    ElMessageBox.confirm('是否确认删除?', '提示', { type: 'warning' })
        .then(() => {
            deleteAgreen(row.id, {
                onSuccess: () => {
                    ElMessage.success('删除成功')
                },
            })
        })
}
const operateMap = {
    [operateType.initialA.value]: (row: any) => { initialAHandler(row) },
    [operateType.edit.value]: (row: any) => { goShow(row) },
    [operateType.delete.value]: (row: any) => { deleteDraf(row) },
    [operateType.view.value]: (row: any) => {
        goShow(row)
    },
    [operateType.disabled.value]: (row: any) => { stopInfo(row) },
    [operateType.sign.value]: (row: any) => { goShow(row) },

}
function operateHandler(type: string, row: any) {
    console.log(type, row)
    operateMap[type](row)
}
function exportHandler() {
    const formData = cloneDeep(unref(form))

    console.log('exportHandler', formData)
    exportAgreen(formData, {
        onSuccess: (res: any) => {
            const objectUrl = URL.createObjectURL(res)
            location.href = objectUrl
            URL.revokeObjectURL(objectUrl)
        },
    })
}
</script>

<template>
    <ElCard mb-20>
        <SearchForm v-bind="form"
                    :columns="schema"
                    submit-text="查询"
                    @submit="searchSubmit"
                    @reset="reset"
        />
    </ElCard>

    <ElCard>
        <el-button v-if="isPurchaser"
                   type="primary"
                   @click="addShow"
        >
            新增协议
        </el-button>

        <el-button v-if="isAdmin"
                   type="primary"
                   :loading="exportAgrenIsPending"
                   @click="exportHandler"
        >
            导出协议
        </el-button>

        <SearchTable v-bind="gridOptions"
                     ref="tableRef"
                     v-model:pager="gridOptions.pagerConfig"
                     :loading="tableLoading"
                     @page-change="handlePageChange"
        >
            <!-- <template #agreementType="{ row }">
                {{ filterLabel(agreementTypeOptions, row.agreementType) }}
            </template> -->

            <template #source="{ row }">
                {{ sourceEnum.getLabel(row.source) }}
            </template>

            <template #agreementState="{ row }">
                {{ agreementEnum.getLabel(row.status) }}
            </template>

            <template #operate="{ row }">
                <div class="flex gap-20 w-full justify-center">
                    <!-- <span class="text-#da0004 cursor-pointer"
                          @click="goShow(row)"
                    >
                        查看
                    </span>

                    <span v-if="showAdd(row)"
                          class="cursor-pointer"
                          @click="goAdd(row)"
                    >
                        下单
                    </span>

                    <span v-if="showAdd(row.agreementState)"
                          class="cursor-pointer"
                          @click="stopInfo(row)"
                    >
                        停用
                    </span> -->

                    <template v-if="row.status !== agreementStatusEnum.initialA.value && row.flag === FlagStatusEnum.no.value">
                        <span class="text-#da0004 cursor-pointer"
                              @click="operateHandler(operateType.view.value, row)"
                        > {{ operateType.view.label }}  </span>
                    </template>

                    <template v-else>
                        <span v-for="operate in operateList[row.status]"
                              :key="operate.value"
                              class="text-#da0004 cursor-pointer"
                              @click="operateHandler(operate.value, row)"
                        >
                            {{ operate.label }}
                        </span>
                    </template>
                </div>
            </template>
        </SearchTable>
    </ElCard>
</template>
